import pandas as pd
import os
import json

class PandasInteractive:
    def __init__(self):
        self.df = None
        self.filename = None
        pd.set_option('display.unicode.east_asian_width', True)

    def choose_file(self):
        print("请输入要读取的CSV文件名:")
        files = [x for x in os.listdir('.') if x.split('.')[-1] == 'csv']
        files_dict = dict(zip(range(len(files)), files))
        for key, value in files_dict.items():
            print(f"{key}: {value}")
        try:
            choice = int(input("请输入文件编号："))
            self.filename = files_dict[choice]
            self.df = pd.read_csv(self.filename)
            print("文件读取成功。")
        except (FileNotFoundError, KeyError, ValueError):
            print("文件未找到或输入无效，请重新输入。")
            self.choose_file()
        with pd.option_context('display.max_rows', 20,
                       'display.max_columns', 20,
                       'display.precision', 3,
                       'display.max_colwidth', 10
                       ):
            print(self.df)

    def show_menu(self):
        print("\n请选择要进行的操作：")
        print("1. 查看数据")
        print("2. 增加数据")
        print("3. 删除数据")
        print("4. 修改数据")
        print("5. 退出")
        choice = int(input("请输入操作编号："))
        if choice == 1:
            self.view_data()
        elif choice == 2:
            self.add_data()
        elif choice == 3:
            self.delete_data()
        elif choice == 4:
            self.modify_data()
        elif choice == 5:
            exit()
        else:
            print("无效的操作编号，请重新输入。")
            self.show_menu()

    def view_data(self):
        while True:
            print("\n请选择查看行还是列：")
            print("1. 查看行")
            print("2. 查看列")
            print("3. 返回上一级")
            choice = int(input("请输入操作编号："))
            if choice == 1:
                print(self.df.iloc[:, :2].to_markdown())
                row = int(input("请输入要查看的行号："))
                print(self.df.iloc[row].to_markdown())
            elif choice == 2:
                print(list(self.df.columns))
                col = input("请输入要查看的列名：")
                print(self.df[col].to_markdown())
            elif choice == 3:
                self.show_menu()
            else:
                print("无效的操作编号，请重新输入。")

    def add_data(self):
        try:
            data = {}
            for key in self.df.columns.tolist():
                data_str = input(f"请输入{key}（使用分号分隔,样例：{self.df.loc[0,key]}）：")
                while True:
                    if ',' in data_str:
                        print("数据中不能包含逗号。")
                    break
                data[key]=data_str
            self.df = self.df._append(data, ignore_index=True)
            print("数据添加成功。")
        except json.JSONDecodeError:
            print("JSON格式错误，请重新输入。")
            self.add_data()

    def delete_data(self): 
        print(self.df.iloc[:, :2].to_markdown())
        index = int(input("请输入要删除的行号："))
        self.df = self.df.drop(index)
        print("数据删除成功。")

    def modify_data(self):
        print(self.df.iloc[:, :2].to_markdown())
        index = int(input("请输入要修改的行号："))
        print("可用的关键字：", self.df.columns.tolist())
        key = input("请输入要修改的关键字：")
        value = input(f"现在为'{self.df.at[index, key]}'; 请输入新的值：")
        if ',' in value:
            print("数据中不能包含逗号。")
            self.modify_data()
            return
        self.df.at[index, key] = value
        print("数据修改成功。")

    def run(self):
        self.choose_file()
        while True:
            self.show_menu()

    def __del__(self):
        if self.df is not None and self.filename is not None:
            # 保存修改后的DataFrame到原始的CSV文件
            self.df.to_csv(self.filename, index=False)
            print(f"修改已保存到文件 {self.filename}。")

if __name__ == '__main__': 
    # 运行程序
    PandasInteractive().run()
